package com.fine.demo.temperaturepolyline

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.ViewTreeObserver
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class MainActivity : AppCompatActivity() {

    private lateinit var weathers: MutableList<Weather>
    private val maxTemps = listOf(25, 18, 15, 32, 22, 24, 19, 30, 34, 30, 32, 31, 29, 36)
    private val minTemps = listOf(21, 14, 10, 26, 20, 21, 17, 25, 30, 29, 27, 30, 26, 34)
    private lateinit var mAdapter: TemperatureAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        weathers = mutableListOf()
        fakeWeathers()
        val mRecyclerView = findViewById<RecyclerView>(R.id.recyclerview)
        mRecyclerView.isNestedScrollingEnabled = false
        mRecyclerView.layoutManager = FullyLinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        mAdapter = TemperatureAdapter(this, weathers)
        mRecyclerView.adapter = mAdapter
        val temperaturePolyline = findViewById<TemperaturePolyline>(R.id.temperature_polyline)
        val list = listOf(25, 18, 15, 32, 22, 24, 19, 30, 34, 30, 32, 31, 29, 36)
        temperaturePolyline.refreshTemperature(list)
        val viewTreeObserver = mRecyclerView.viewTreeObserver
        viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener{
            override fun onGlobalLayout() {
                mRecyclerView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val height = mRecyclerView.height
                val width = mRecyclerView.width
                Log.i("wtf", "width1:$width---height1:$height")
                val count = mRecyclerView.childCount
                Log.i("wtf", "count:$count")
                val perItemWidth = width.toFloat() / count
                val totalWidth = perItemWidth * weathers.size
                Log.i("wtf", "totalWidth:$totalWidth")
                temperaturePolyline.setViewWidth(totalWidth.toInt())
            }

        })
    }

    private fun fakeWeathers() {
        for (index in 0 .. 13) {
            val weather = Weather("深圳", "多云", maxTemps[index], minTemps[index])
            weathers.add(weather)
        }
    }
}
